import { fetchLogin, fetchSendCode } from "@/api/server/recommend_question";
import { Condition } from "@/components/Condition";
import { useAppStore } from "@/store";
import { CheckCircleOutlined } from "@ant-design/icons";
import { useLocalStorageState } from "ahooks";
import { Button, Input, message } from "antd";
import { PropsWithChildren, useEffect, useMemo, useRef, useState } from "react";

interface ILoginProps {
  className?: string;
}
export function Login(props: PropsWithChildren<ILoginProps>) {
  const [loginType, setLoginType] = useState("login");
  const setLogined = useAppStore((state) => state.setLogined);
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [time, setTime] = useState(-1);
  const unmounted = useRef(false);
  const [timestamp, setTimestamp] =
    useLocalStorageState<number>("loginCodeTime");
  const isSended = useMemo(() => {
    return time === 0;
  }, [time]);
  const isUnsend = useMemo(() => {
    return time === -1;
  }, [time]);
  const isWait60 = useMemo(() => {
    return time > 0;
  }, [time]);

  const onLogin = async () => {
    const phone_number = phone?.trim();
    const verification_code = code?.trim();
    if (!/^[0-9]{11}$/.test(phone_number)) {
      message.warning("请输入手机号");
      return;
    }

    if (!/^[0-9]{6}$/.test(verification_code)) {
      message.warning("请输入6位验证码");
      return;
    }

    const res = await fetchLogin({
      phone_number,
      verification_code,
    });

    if (!res.data.success) {
      message.warning(res.data.message);
    } else {
      message.success("登录成功！", 2, () => {
        setLogined(true);
        location.reload()
      });
    }
  };

  const onSendCode = async () => {
    const phone_number = phone?.trim();
    if (!/^[0-9]{11}$/.test(phone_number)) {
      message.warning("请输入11位手机号");
      return;
    }

    const res = await fetchSendCode(phone_number);

    if (!res.data.success) {
      message.warning(res.data.message);
    } else {
      const nowTimestamp = Date.now();
      message.success("验证码已发送，注意查收！");
      setTimestamp(nowTimestamp);
      startTime(nowTimestamp);
    }
  };

  const startTime = (nowTimestamp) => {
    const ms = Date.now() - nowTimestamp;

    const m = ms / 1000;
    const t = Math.ceil(60 - m);
    console.log("m", m);

    if (t <= 0) {
      setTime(0);
      setTimestamp(0);
      return;
    }

    setTime(t);

    if (unmounted.current) {
      return;
    }

    requestAnimationFrame(() => {
      startTime(nowTimestamp);
    });
  };

  useEffect(() => {
    if (timestamp > 0) {
      startTime(timestamp);
    }
    unmounted.current = false;
    console.log("mounted");
    return () => {
      console.log("unmounted");
      unmounted.current = true;
    };
  }, []);

  return (
    <div className="absolute flex flex-row justify-center items-center bg-[#00000044] z-10 top-0 bottom-0 w-full h-full">
      <div className="bg-white relative flex flex-col px-[50px] pt-[20px] pb-[40px]">
        <Condition condition={loginType === "login"}>
          <div className="text-[#605ce5] font-[500] text-[18px] border-b border-b-[#605ce5] border-solid py-[10px]">
            手机号登录
          </div>
        </Condition>
        <Condition condition={loginType === "registry"}>
          <div
            onClick={() => setLoginType("login")}
            className="absolute right-0 top-0 w-[69px] h-[69px] flex flex-row justify-end pt-[10px] pr-[5px] text-white cursor-pointer"
            style={{
              clipPath: "polygon(0% 0%, 100% 0%, 100% 100%)",
              backgroundImage:
                "linear-gradient(to right bottom, rgb(186, 172, 255), rgb(48, 128, 255))",
            }}
          >
            <span>登录</span>
          </div>

          <div className="text-[#605ce5] font-[500] text-[18px] border-b border-b-[#605ce5] border-solid py-[10px]">
            手机号注册
          </div>
        </Condition>
        <div
          className="items-center w-[280px] flex flex-row text-[14px] border-b border-b-[#d7d8d9] border-solid hover:border-b-[#605ce5] mt-[30px]"
          style={{ color: "rgba(22,26,35,.55)" }}
        >
          <div>+86</div>
          <Input
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            variant="borderless"
            placeholder="请输入手机号"
            className="flex-1 min-w-0"
          />
        </div>
        <div
          className="items-center w-[280px] flex flex-row text-[14px] border-b border-b-[#d7d8d9] border-solid hover:border-b-[#605ce5] mt-[10px]"
          style={{ color: "rgba(22,26,35,.55)" }}
        >
          <Input
            value={code}
            onChange={(e) => setCode(e.target.value)}
            variant="borderless"
            placeholder="请输入验证码"
            className="flex-1 min-w-0"
          />
          <Condition condition={isSended}>
            <div
              onClick={() => onSendCode()}
              className="text-[#605ce5] pl-[14px] cursor-pointer whitespace-nowrap border-l border-l-[#d7d8d9] border-solid"
            >
              重新发送
            </div>
          </Condition>
          <Condition condition={isUnsend}>
            <div
              onClick={() => onSendCode()}
              className="pl-[14px] cursor-pointer whitespace-nowrap border-l border-l-[#d7d8d9] border-solid"
            >
              获取验证码
            </div>
          </Condition>
          <Condition condition={isWait60}>
            <div className="pl-[14px] cursor-pointer whitespace-nowrap border-l border-l-[#d7d8d9] border-solid">
              ({time})秒重新获取
            </div>
          </Condition>
        </div>
        <div className="flex flex-row items-center mt-[10px] text-[12px] text-[#26244c] gap-[6px]">
          <Condition condition={isSended || isWait60}>
            <CheckCircleOutlined color="#038024" />
            <span>短信验证码已发送，可能会有延后，请耐心等待</span>
          </Condition>
        </div>
        <Condition condition={loginType === "login"}>
          <div className="mt-[30px] w-[280px]">
            <Button
              onClick={() => onLogin()}
              type="primary"
              block
              disabled={!phone || !code}
            >
              一键登录/注册
            </Button>
          </div>
        </Condition>
        <Condition condition={loginType === "registry"}>
          <div className="mt-[30px] w-[280px]">
            <Button type="primary" block>
              注册
            </Button>
          </div>
        </Condition>
      </div>
    </div>
  );
}
